<template>
  <el-dialog
    v-model="visible"
    :title="categoryId ? '编辑分类' : '新增分类'"
    width="600px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
    >
      <el-form-item label="分类名称" prop="categoryName">
        <el-input v-model="form.categoryName" placeholder="请输入分类名称" />
      </el-form-item>

      <el-form-item label="父分类" prop="parentId">
        <el-select
          v-model="form.parentId"
          placeholder="请选择父分类（不选则为顶级分类）"
          style="width: 100%"
          clearable
        >
          <el-option
            v-for="cat in flatCategories"
            :key="cat.id"
            :label="cat.categoryName"
            :value="cat.id"
            :disabled="categoryId === cat.id"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="排序" prop="sortOrder">
        <el-input-number
          v-model="form.sortOrder"
          :min="0"
          :step="1"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item label="分类图标">
        <el-input v-model="form.icon" placeholder="请输入图标URL（可选）" />
      </el-form-item>

      <el-form-item label="分类描述">
        <el-input
          v-model="form.description"
          type="textarea"
          :rows="3"
          placeholder="请输入分类描述"
        />
      </el-form-item>

      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">启用</el-radio>
          <el-radio :label="0">禁用</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" :loading="submitting" @click="handleSubmit">
        确定
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { getCategoryDetail, createCategory, updateCategory } from '@/api/category'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  categoryId: {
    type: Number,
    default: null
  },
  parentCategories: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'success'])

const visible = ref(false)
const submitting = ref(false)
const formRef = ref(null)

const form = reactive({
  categoryName: '',
  parentId: null,
  sortOrder: 0,
  icon: '',
  description: '',
  status: 1
})

const rules = {
  categoryName: [
    { required: true, message: '请输入分类名称', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 扁平化分类列表（用于选择父分类）
const flatCategories = computed(() => {
  const flatten = (categories, level = 0) => {
    let result = []
    categories.forEach(cat => {
      result.push({ ...cat, level })
      if (cat.children && cat.children.length > 0) {
        result = result.concat(flatten(cat.children, level + 1))
      }
    })
    return result
  }
  return flatten(props.parentCategories)
})

// 加载分类详情
const loadCategoryDetail = async () => {
  if (!props.categoryId) {
    resetForm()
    return
  }

  try {
    const res = await getCategoryDetail(props.categoryId)
    if (res.code === 200 && res.data) {
      Object.assign(form, {
        categoryName: res.data.categoryName || '',
        parentId: res.data.parentId || null,
        sortOrder: res.data.sortOrder || 0,
        icon: res.data.icon || '',
        description: res.data.description || '',
        status: res.data.status !== undefined ? res.data.status : 1
      })
    }
  } catch (error) {
    console.error('加载分类详情失败:', error)
    ElMessage.error('加载分类详情失败')
  }
}

// 提交表单
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    submitting.value = true

    const categoryData = {
      ...form,
      parentId: form.parentId || 0
    }

    const res = props.categoryId
      ? await updateCategory(props.categoryId, categoryData)
      : await createCategory(categoryData)

    if (res.code === 200) {
      ElMessage.success(props.categoryId ? '更新成功' : '创建成功')
      emit('success')
      handleClose()
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    if (error !== false) {
      console.error('提交失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    categoryName: '',
    parentId: null,
    sortOrder: 0,
    icon: '',
    description: '',
    status: 1
  })
  formRef.value?.clearValidate()
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  resetForm()
  emit('update:modelValue', false)
}

// 监听visible变化
watch(() => props.modelValue, (val) => {
  visible.value = val
  if (val) {
    loadCategoryDetail()
  }
})

// 监听visible变化同步到props
watch(visible, (val) => {
  emit('update:modelValue', val)
})
</script>

<style lang="scss" scoped>
</style>
